package com.ikun.hosuserservice.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.ikun.common.entity.ResponseResult;
import com.ikun.common.entity.User;
import com.ikun.common.utils.JwtUtils;
import com.ikun.common.utils.RsaUtils;
import com.ikun.hosuserservice.config.WXConfigurationProperties;
import com.ikun.hosuserservice.service.WxLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信登录相关的控制器
 */
@Slf4j
@RequestMapping("/api/ucenter/wx")
@Controller
public class WXLoginController {

    @Resource
    private WXConfigurationProperties wxConfigurationProperties;
    @Resource
    private WxLoginService wxLoginService;

    /**
     * 微信授权成功的回调方法
     * @param code
     * @return
     */
    @RequestMapping("callback")
    public String callback(String code) throws Exception {
        log.info("code:{}",code);
        //微信登录获得学员信息
        User user = wxLoginService.wxLogin(code);
        //生成本地access-token
        String accessToken = JwtUtils.generateUserToken(user, RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
        ResponseResult<User> res = ResponseResult.ok(user, accessToken, "");
        String json = new ObjectMapper().writeValueAsString(res);
        //重定向到前端页面，保存用户信息
        return "redirect:" + wxConfigurationProperties.getWebCallbackURL() + json;
    }

    /**
     * 提供微信登录所需参数
     * @return
     */
    @GetMapping("getWxParam")
    @ResponseBody
    public ResponseResult<Map> getWxParam(){
        Map<String,String> params = new HashMap<>();
        params.put("appid",wxConfigurationProperties.getAppId());
        params.put("redirectUri",wxConfigurationProperties.getRedirectURL());
        params.put("scope","snsapi_login");
        params.put("state", System.currentTimeMillis()+"");
        return ResponseResult.ok(params);
    }
}
